using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneLoader : MonoBehaviour
{
    public static SceneLoader sceneLoader;
    public LoadingScreen loadingScreen;

    public void Awake()
    {
        sceneLoader = this;
    }
    public void LoadScene(string name)
    {
        SceneManager.LoadScene(name, LoadSceneMode.Additive);
    }

    public void LoadSceneAsync(string name, bool showLoading = false)
    {
        StopAllCoroutines();
        var op = SceneManager.LoadSceneAsync(name, LoadSceneMode.Additive);
        op.allowSceneActivation = true;
        StartCoroutine("Progress", op);
    }

    private IEnumerator Progress(AsyncOperation op)
    {
        loadingScreen.progress = 0f;//reset
        var loadingScreenWindow = loadingScreen.GetComponent<Window>();
        loadingScreenWindow.Show();
        while (loadingScreen.GetComponent<Window>().IsAnimating)
        {
            yield return null;
        }
        do
        {
            loadingScreen.progress = op.progress;
            yield return null;
        } while (!op.isDone);
        loadingScreen.progress = op.progress;
        yield return new WaitForSecondsRealtime(1.5f);
        loadingScreenWindow.Hide();

    }

    public void UnloadSceneAsync(string name)
    {
        SceneManager.UnloadSceneAsync(name);
    }
}


